package com.ruoyi.file.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.file.domain.FileAttachmentInfo;
import com.ruoyi.file.domain.Kv;
import com.ruoyi.file.dto.FileAttachmentInfoDto;
import com.ruoyi.file.mapper.FileAttachmentInfoMapper;
import com.ruoyi.file.service.IFileAttachmentInfoService;
import com.ruoyi.file.service.IIdCardInfoService;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.file.utils.IdWorker;
import com.ruoyi.file.utils.OBSUtil;
import com.ruoyi.file.vo.FileAttachmentInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;


@Service
@EnableScheduling
public class FileAttachmentInfoServiceImpl implements IFileAttachmentInfoService {
    @Autowired
    private ISysFileService fileService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private FileAttachmentInfoMapper fileAttachmentInfoMapper;

    @Autowired
    private OBSUtil obsUtil;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IIdCardInfoService idCardInfoService;

    @Value("${ocr.ak}")
    private String ak;

    @Value("${ocr.sk}")
    private String sk;

    @Value("${ocr.projectId}")
    private String projectId;

    @Value("${ocr.endpoint}")
    private String endpoint;


    @Value("${aliyun.ocr.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.ocr.accessKeySecret}")

    private String accessKeySecret;

    @Value("${aliyun.ocr.endpoint}")
    private String aliyunocrendpoint;

    /***
     *  只需要单纯的 把附件传到obs即可。
     * @param file
     * @param tableName
     * @param colName
     * @param associationId
     * @return
     * @throws Exception
     */
    @Override
    public FileAttachmentInfo uploadFile(MultipartFile file, String tableName, String colName, String associationId, String watermark) throws Exception {
        // 保存文件到obs
        String uploadResult = fileService.uploadFile(file, tableName, colName, watermark);
        Map<String, String> obsMap = StringUtils.parseResultMapString(uploadResult);

        // 创建文件附件记录并保存到对象中
        // 生成ROW_ID
        String rowId = "FJ" + idWorker.nextId();
        FileAttachmentInfo fileInfo = new FileAttachmentInfo();
        fileInfo.setOrgCode(watermark);
        // 设置记录编号
        fileInfo.setId(rowId);
        // 设置附件类型
        fileInfo.setTableName(tableName);
        // 设置文件原始名称
        fileInfo.setFileName(obsMap.get("fileName"));
        // 设置文件存储名称
        fileInfo.setFileStorageName(obsMap.get("fileStorageName"));
        // 设置文件存储路径
        fileInfo.setFilePath(obsMap.get("objectKey"));

        // 设置文件是否为图片
        fileInfo.setFileExtension(obsMap.get("fileExtension"));

        // 设置文件上传时间
        fileInfo.setCreateDate(DateUtils.getCurrentTime());
        // 设置上传人员ID
        if (StringUtils.isEmpty(SecurityUtils.getUsername())) {
            fileInfo.setCreateUser("小程序");
        } else {
            fileInfo.setCreateUser(SecurityUtils.getUsername());
        }

        fileInfo.setAssociationId(associationId);
        // 设置分类标识 - 用于区分单据和车辆的上传与预览
        fileInfo.setColName(colName);
        fileInfo.setOriginalFileName(obsMap.get("originalFileName"));
        // 设置主体信息对象
        // 将对象保存到数据库中
        fileAttachmentInfoMapper.insertFileAttachmentInfo(fileInfo);
        return fileInfo;

    }

    @Override
    public int deleteFileAttachmentInfoByIds(String[] ids) {
        return 0;
    }

    @Override
    public List<FileAttachmentInfoVo> selectFileAttachmentInfoList(FileAttachmentInfoDto fileAttachmentInfo) throws IOException {
        List<FileAttachmentInfo> fileAttachmentInfos = fileAttachmentInfoMapper.selectFileAttachmentInfoList(fileAttachmentInfo);

        List<FileAttachmentInfoVo> fileAttachmentInfoList = new ArrayList<>();

        for (FileAttachmentInfo atachment : fileAttachmentInfos) {
            // 根据传入编号以及分类标识获取文件(分类标识用于判断获取的是单据还是车辆)对应的存储路径
            if (atachment.getFilePath() != null) {
                // redis - key
                String objectKey = atachment.getId();
                // redis - value
                String fileBytes = null;
                if (redisService.hasKey(objectKey)) {// redis中存在，直接从redis取出返回结果
                    fileBytes = (String) redisService.getCacheObject(objectKey);
                } else {// redis中不存在, 先存redis再返回
                    // 调用OBS文件读取流方法，处理文件并添加到键值对中
                    byte[] obsFileBytes = obsUtil.downloadFileAsBytes(atachment.getFilePath());
                    fileBytes = Base64.getEncoder().encodeToString(obsFileBytes);
                    redisService.setCacheObject(objectKey, fileBytes);
                }
                FileAttachmentInfoVo vo = new FileAttachmentInfoVo();

                BeanUtils.copyBeanProp(vo, atachment);

                vo.setFileBytes(fileBytes);
                fileAttachmentInfoList.add(vo);
            }
        }

        return fileAttachmentInfoList;
    }

    @Override
    public HashMap<String, Object> uploadAttachment(MultipartFile file, String tableName, String colName, String associationId, String watermark) throws Exception {
//        if ("idCardImg".equalsIgnoreCase(colName) || "id_card".equalsIgnoreCase(colName)) {
//            tableName = "sys_id_card_info";
//            if (colName.toLowerCase().contains("back")) {
//                colName = "id_card_back_img";
//            } else {
//                colName = "id_card_img";
//            }
//        }
//        if ("driverLicenseBackImg".equalsIgnoreCase(colName)) {
//            colName = "driver_license_back_img";
//        }
        FileAttachmentInfo fileInfo = this.uploadFile(file, tableName, colName, associationId, watermark);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("vo", fileInfo);
        resultMap.put("url", "/dev-api/file/fileAttachmentInfo/viewImage?key=" + fileInfo.getId());
//        resultMap.put("url", "https://data.lvlianhengsheng.com/dev-api/file/fileAttachmentInfo/viewImage?key=" + fileInfo.getId());
        return resultMap;


//                if ("idCard".equalsIgnoreCase(colName ) || "id_card_img".equalsIgnoreCase(colName )  || "id_card".equalsIgnoreCase(colName )  ) {
        // 获取文件的Base64编码
/*            if (colName.contains("businessLicense") || colName.contains("driverLicense") || colName.toLowerCase().contains("card") || "id_card".equalsIgnoreCase(colName) || "id_card_img".equalsIgnoreCase(colName) || colName.contains("vehicleLicense")) {
                // 获取文件的Base64编码
                byte[] fileBytes = file.getBytes();
                String base64EncodedFile = Base64.getEncoder().encodeToString(fileBytes);
                // 调用ocr接口
//                OCRUtil ocrUtil = new OCRUtil();

//                HashMap<String, Object> ocrResult = ocrUtil.getOcr(base64EncodedFile, fileInfo.getColName(), ak, sk, projectId, endpoint, accessKeyId, accessKeySecret, aliyunocrendpoint);

  *//*              if (ocrResult.get("id_card") != null) {
                    IdCardResultVo idCard = (IdCardResultVo) ocrResult.get("id_card");
                    IdCardInfo targetPo = new IdCardInfo();
                    BeanUtils.copyProperties(idCard, targetPo);
                    targetPo.setIdCard(idCard.getNumber());
                    targetPo.setGender(idCard.getSex());
                    targetPo.setEthnicity(idCard.getEthnicity());
                    targetPo.setBirthDate(idCard.getBirth());
                    targetPo.setIdCardImg(fileInfo.getId());
                    targetPo.setName(idCard.getName());


                    targetPo.setCreateUser(SecurityUtils.getUsername());
                    targetPo.setCreateDate(DateUtils.getCurrentTime());

                    if (StringUtils.isNotEmpty(targetPo.getIdCard())) {
                        targetPo.setId(MD5Utils.md5(targetPo.getIdCard()));
                        idCardInfoService.insertIdCardInfo(targetPo);
                    }
                }*//*
//                resultMap.put("ocr", ocrResult);
            }*/

//        try {
//            boolean flag = true;
//            if (colName.contains("avatar")) {
//                int avatarcnt = fileAttachmentInfoMapper.flushHeadAvatar(associationId);
//                return resultMap;
//            }
//            int businessLicensecnt = 0;
//
//            if ("businessLicense".equalsIgnoreCase(colName)) {
//                colName = "company_img";
//                businessLicensecnt = fileAttachmentInfoMapper.flushBusinessLicenseImg(tableName, colName, associationId, "company_code");
//                flag = false;
//            }
//            if ("driverLicenseImg".equalsIgnoreCase(colName) || "driver_license_img".equalsIgnoreCase(colName)) {
//                colName = "driver_license_img";
//                businessLicensecnt = fileAttachmentInfoMapper.flushBusinessLicenseImg(tableName, colName, associationId, "license_no");
//                flag = false;
//            }
//            if ("driverLicenseBackImg".equalsIgnoreCase(colName) || "driver_license_back_img".equalsIgnoreCase(colName)) {
//                colName = "driver_license_back_img";
//                businessLicensecnt = fileAttachmentInfoMapper.flushIdcardBackImg(tableName, colName, associationId.substring(0, 11), "phone_no");
//                flag = false;
//            }
////先整背面
//            if ("idCardBackImg".equalsIgnoreCase(colName) || "id_card_back_img".equalsIgnoreCase(colName)) {
//                businessLicensecnt = fileAttachmentInfoMapper.flushIdcardBackImg("sys_id_card_info", "id_card_back_img", associationId.substring(0, 11), "phone");
//                flag = false;
//            }
//
//            if ("id_card_img".equalsIgnoreCase(colName) || colName.toLowerCase().contains("card") || colName.equalsIgnoreCase("idCard")) {
//                businessLicensecnt = fileAttachmentInfoMapper.flushBusinessLicenseImg(tableName, "id_card", associationId, "id_card");
//                flag = false;
//            }
//
//            if ("headImg".equalsIgnoreCase(colName)) {
//                colName = "head_img";
//            }
//            if ("drivingLicenseBackImg".equalsIgnoreCase(colName)) {
//                colName = "driving_license_img";
//            }
//            if ("drivingLicenseBackImg".equalsIgnoreCase(colName)) {
//                colName = "driving_license_back_img";
//            }
//
//            if ("drivingLicenseImg".equalsIgnoreCase(colName)) {
//                colName = "driving_license_img";
//            }
//
//            if (flag) {
//                businessLicensecnt = fileAttachmentInfoMapper.flushBusinessLicenseImg(tableName, colName, associationId, "id");
//            }
//
//            System.out.println(tableName + "=================================================" + colName + "-----------------------------" + associationId);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    // 将记录id返回给前端
//        return resultMap;
    }

    @Override
    public FileAttachmentInfo selectFileAttachmentInfoById(String id) {
        return fileAttachmentInfoMapper.selectFileAttachmentInfoById(id);
    }


    @Override
    public List<Kv> fileDetails(List<String> ids, String tableName, String colName) throws IOException {
        List<Kv> FileList = new ArrayList<>();

        for (String rowId : ids) {
            // 根据传入编号以及分类标识获取文件(分类标识用于判断获取的是单据还是车辆)对应的存储路径
            String obsFilePath = fileAttachmentInfoMapper.getFilePath(rowId, tableName, colName);
            if (obsFilePath != null) {
                // 调用OBS文件读取流方法，处理文件并添加到键值对中
                byte[] obsFileBytes = obsUtil.downloadFileAsBytes(obsFilePath);
                String fileBytes = Base64.getEncoder().encodeToString(obsFileBytes);

                Kv kv = Kv.create().set("key", rowId).set("file", fileBytes);
                FileList.add(kv);
            }
        }
        return FileList;
    }

    @Override
    public byte[] getDownloadUrl(String objectKey) throws IOException {
        String path = fileAttachmentInfoMapper.getFilePath(objectKey, null, null);
        String prefix = "https://fk-file-bucket.obs.cn-north-4.myhuaweicloud.com/";

        if (StringUtils.isNotEmpty(path) && path.startsWith(prefix)) {
            path = path.substring(prefix.length());
        }
        byte[] obsFileBytes = obsUtil.downloadFileAsBytes(path);

        return obsFileBytes;
    }

    @Override
    public String getObjectUrlByKey(String objectKey) throws IOException {
        String downloadUrl = obsUtil.getDownloadUrl(objectKey);

        return downloadUrl;
    }


    public static void main(String[] args) {

/*        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.afterPropertiesSet();
        String fileBytes = (String) redisTemplate.opsForValue().get("222");
        // 将 base64转成图片
        String path = "D:/image/";
        boolean b = Base64ToImage.base64StrToImage(fileBytes, path);
        if (b){
            System.out.println("图片转化成功！！");
        }*/

//        for (int i = 0;i<5;i++){
//            System.out.println("D:\\image\\myfile"+i+".jpg");
//        }
    }
}


